package com.hghivln.blog.controller;


import com.hghivln.blog.common.lang.Result;
import com.hghivln.blog.common.lang.ResultEnum;
import com.hghivln.blog.common.lang.UserTypeEnum;
import com.hghivln.blog.entity.SysUser;
import com.hghivln.blog.entity.User;
import com.hghivln.blog.pojo.dto.UpdatePwdDto;
import com.hghivln.blog.pojo.vo.TokenVo;
import com.hghivln.blog.service.UserService;
import com.hghivln.blog.shiro.LoginToken;
import com.hghivln.blog.shiro.LoginUser;
import com.hghivln.blog.utils.IdWorker;
import com.hghivln.blog.utils.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author hghivln
 * @since 2021-09-24
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;


    @PostMapping("/register")
    public Result<?> register(@RequestBody User user) {
        userService.save(user);
        return new Result<>("注册成功！");
    }

    @PostMapping("login")
    public Result<?> login(@RequestBody User user) {
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken authenticationToken = new LoginToken(user.getUsername(),user.getPassword(), UserTypeEnum.USER);
        try {
            subject.login(authenticationToken);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return new Result<>(ResultEnum.LOGIN_PARAM_ERROR);
        }
        String token = subject.getSession().getId().toString();
        return new Result<>(new TokenVo(token));
    }

    /**
     * 获取当前登录用户
     */
    @GetMapping("info")
    public Result<LoginUser> info(){
        LoginUser user = ShiroUtils.getLoginUser();
        return new Result<>(user);
    }

    @PostMapping("logout")
    public Result<?> logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return new Result<>("退出成功！");
    }

    /**
     * 修改密码
     */
    @PutMapping("updatePwd")
    public Result<?> updatePwd(@RequestBody UpdatePwdDto updatePwdDto) {
        try {
            userService.updatePwd(updatePwdDto);
            return new Result<>("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result<>(e.getMessage());
        }
    }

    /**
     * 修改用户
     */
    @PutMapping("update")
    public Result<?> update(@RequestBody User user) {
        try {
            userService.updateById(user);
            return new Result<>("修改成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result<>("修改失败！");
        }
    }

}
